﻿using LPP.Entity.PaymentRecord;
using LPP.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;


namespace LPP.Repository.PaymentRecordRepository
{
    public class PaymentRecordRepository : IPaymentRecordRepository
    {
        private readonly SqlDbContext _context;
        private readonly ILogger<PaymentRecordRepository> _logger;

        public PaymentRecordRepository(
           SqlDbContext context,
            ILogger<PaymentRecordRepository> logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task<PaymentRecord> AddAsync(PaymentRecord record)
        {
            try
            {
                await _context.PaymentRecords.AddAsync(record);
                await _context.SaveChangesAsync();
                return record;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加支付记录失败: {@Record}", record);
                throw;
            }
        }

        public async Task<PaymentRecord> GetByOrderIdAsync(string orderId)
        {
            try
            {
                return await _context.PaymentRecords
                    .FirstOrDefaultAsync(x => x.OrderId == orderId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取支付记录失败: OrderId={OrderId}", orderId);
                throw;
            }
        }

        public async Task<PaymentRecord> UpdateAsync(PaymentRecord record)
        {
            try
            {
                _context.PaymentRecords.Update(record);
                await _context.SaveChangesAsync();
                return record;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新支付记录失败: {@Record}", record);
                throw;
            }
        }

        public async Task<List<PaymentRecord>> GetPaymentRecordsByStatusAsync(PaymentStatus status)
        {
            try
            {
                return await _context.PaymentRecords
                    .Where(x => x.Status == status)
                    .OrderByDescending(x => x.CreatedAt)
                    .ToListAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取支付记录列表失败: Status={Status}", status);
                throw;
            }
        }

        public async Task<bool> ExistsAsync(string orderId)
        {
            try
            {
                return await _context.PaymentRecords
                    .AnyAsync(x => x.OrderId == orderId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查支付记录是否存在失败: OrderId={OrderId}", orderId);
                throw;
            }
        }
    }
}
